from typing import Optional
from fastapi import Request, status
from fastapi.responses import JSONResponse
from utils.logger import Logger
from utils.constants import ErrorCode
from config import settings

logger = Logger.get_logger(agent_name="auth_middleware")

async def auth_middleware(request: Request, call_next):
    """鉴权中间件：验证API Key或JWT令牌"""
    # 跳过无需鉴权的接口（如根路径、状态接口）
    skip_paths = ["/", "/api/v1/status"]
    if request.url.path in skip_paths or request.method == "OPTIONS":
        return await call_next(request)

    # 未启用鉴权（开发环境），直接放行
    # 注意：SecurityConfig中没有enable_auth属性，暂时默认放行所有请求
    logger.debug(f"鉴权未启用，放行请求: path={request.url.path}, request_id={request.state.request_id}")
    return await call_next(request)

    # 1. 从请求头获取鉴权信息（优先API Key，其次JWT）
    api_key = request.headers.get("API-Key")
    jwt_token = request.headers.get("Authorization")

    # 2. 验证API Key
    if api_key:
        if api_key in settings.security.api_keys:
            logger.debug(f"API Key验证通过: request_id={request.state.request_id}")
            return await call_next(request)
        logger.warning(f"API Key验证失败: request_id={request.state.request_id}, api_key={api_key[:6]}***")
        return JSONResponse(
            status_code=status.HTTP_401_UNAUTHORIZED,
            content={
                "code": ErrorCode.PARAM_ERROR.value,
                "message": "无效的API Key",
                "data": {"request_id": request.state.request_id}
            }
        )

    # 3. 验证JWT（简化实现，实际需用PyJWT解析验证）
    if jwt_token and jwt_token.startswith("Bearer "):
        token = jwt_token.split(" ")[1]
        try:
            # 模拟JWT验证（实际需用 security_config.auth.jwt_secret 解密）
            if len(token) >= 16:  # 简单校验令牌长度
                logger.debug(f"JWT验证通过: request_id={request.state.request_id}")
                # 解析token获取user_id，存入request.state供后续使用
                request.state.user_id = "user_" + token[:8]
                return await call_next(request)
        except Exception as e:
            logger.error(f"JWT验证异常: request_id={request.state.request_id}, error={str(e)}")

    logger.warning(f"鉴权失败: 未提供有效API Key或JWT令牌，request_id={request.state.request_id}")
    return JSONResponse(
        status_code=status.HTTP_401_UNAUTHORIZED,
        content={
            "code": ErrorCode.PARAM_ERROR.value,
            "message": "请提供有效的API Key或Authorization令牌",
            "data": {"request_id": request.state.request_id}
        }
    )